package com.eden.api.controller;

import com.eden.api.controller.vo.ApiLoginReq;
import com.eden.api.controller.vo.ApiLoginResp;
import com.eden.api.controller.vo.ApiResult;
import com.eden.api.controller.vo.SchoolUserVo;
import com.eden.api.security.JwtUser;
import com.eden.api.security.LoginUser;
import com.eden.api.security.annotation.AnonymousAccess;
import com.eden.api.security.service.ApiLoginService;
import com.eden.common.constant.HttpStatus;
import com.eden.common.utils.StringUtils;
import com.eden.school.domain.SchoolUser;
import com.eden.school.service.ISchoolUserService;
import com.eden.system.domain.SysDept;
import com.eden.system.service.ISysDeptService;
import com.eden.task.domain.UserTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @program: eden
 * @description: 客户端登录（移动端、小程序，前后分离PC、三方...）
 * @author: Mr.Jiao
 * @create: 2020-09-14 17:28
 */

@Slf4j
@Api("客户端登录接口")
@RestController
@RequestMapping("/api")
public class ApiLoginController extends ApiBaseController {

    @Value("${api.token.header}")
    private String header;

    @Autowired
    private ApiLoginService loginService;
    @Autowired
    private ISchoolUserService schoolUserService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 用户登录接口
     *
     * @param apiLoginReq
     * @return
     */
    @ApiOperation("学校用户登录接口")
    @ApiImplicitParam(name = "apiLoginReq", value = "登录请求", required = true, dataType = "ApiLoginReq")
    @AnonymousAccess
    @PostMapping("/login")
    public ApiResult login(@Validated @RequestBody ApiLoginReq apiLoginReq) {
        SchoolUserVo userVo = new SchoolUserVo();
        try {
            ApiLoginResp apiLoginResp = loginService.login(apiLoginReq);
            setHeader(header, apiLoginResp.getToken());
            SchoolUser user = schoolUserService.selectSchoolUserByLoginName(apiLoginReq.getUsername());
            SysDept sysDept = sysDeptService.selectDeptById(user.getDept().getParentId());
            userVo.setLoginName(user.getLoginName());
            userVo.setUserName(user.getUserName());
            userVo.setAvatar(user.getAvatar());
            userVo.setSex(user.getSex());
            userVo.setEmail(user.getEmail());
            userVo.setPhonenumber(user.getPhonenumber());
            userVo.setDeptId(user.getDeptId());
            userVo.setCollegeName(sysDept.getDeptName());
            userVo.setMajor(user.getDept().getDeptName());
            apiLoginResp.setSchoolUser(userVo);
            return ApiResult.success(apiLoginResp);
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(HttpStatus.UNAUTHORIZED, msg);
        }
    }

    /**
     * 用户登录接口
     *
     * @return
     */
    @ApiOperation("查询用户信息")
    @GetMapping("/selectUser")
    public ApiResult selectUser() {
        SchoolUserVo userVo = new SchoolUserVo();
        LoginUser loginUser = JwtUser.getInstance().getLoginUser();
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getLoginName())) {
            SchoolUser user = schoolUserService.selectSchoolUserByLoginName(loginUser.getLoginName());
            SysDept sysDept = sysDeptService.selectDeptById(user.getDept().getParentId());
            userVo.setLoginName(user.getLoginName());
            userVo.setUserName(user.getUserName());
            userVo.setAvatar(user.getAvatar());
            userVo.setSex(user.getSex());
            userVo.setEmail(user.getEmail());
            userVo.setPhonenumber(user.getPhonenumber());
            userVo.setDeptId(user.getDeptId());
            userVo.setCollegeName(sysDept.getDeptName());
            userVo.setMajor(user.getDept().getDeptName());
        }
        return success(userVo);
    }


    @AnonymousAccess
    @GetMapping("/logout")
    public ApiResult logout() {
        loginService.logout();
        return success("退出成功");
    }

    /**
     * 查询用户头像地址
     */
    @ApiOperation("查询用户按照用户")
    @ApiImplicitParam(name = "loginName", value = "查询用户头像", required = true, dataType = "String")
    @AnonymousAccess
    @GetMapping("/selectAvatar")
    public ApiResult selectAvatar(@RequestParam(value = "loginName") String loginName) {
        if (StringUtils.isNotEmpty(loginName)) {
            String avatar = schoolUserService.selectAvatar(loginName);
            if (StringUtils.isNotNull(avatar) && StringUtils.isNotEmpty(avatar)) {
                return success("查询成功!", avatar);
            }
        }
        return error(HttpStatus.NOT_FOUND, "用户不存在");
    }


    /**
     * 学校用户发布任务接口
     */
    @ApiOperation("学校用户发布任务接口")
    @ApiImplicitParam(name = "apiAddTask", value = "学校用户发布任务接口", required = true, dataType = "UserTask")
    @PostMapping("/addTask")
    public ApiResult addTask(@Validated @RequestBody UserTask userTask) {
        return error("", "");
    }
}
